import React, { useState, useEffect } from 'react';
import "./postDetails.scss";
import TablePostDetais from '../../../../components/table_postDetails';
import CardPost from '../../../../components/card_post';
import { getPostDetail,getPostDetail2, getPostDetailList, getNavDetail, searchNav,getDataList } from '../../../../api/api';

import { message } from 'antd';

const PostDetails = (props) => {
    const id = props.location.state.id ? props.location.state.id : "";

    const status = window.sessionStorage.getItem('status');

    const [postObj, setPostObj] = useState({});

    const [navList, setNavList] = useState([]);

    const [navId, setNavId] = useState('');

    const [navItemObj, setNavItemObj] = useState({});

    const [searchTitle, setSearch] = useState("");

    const getDataedList = async (id) => {
        let { data } = await getDataList({ stationVersionId: id });
        message.success(data.msg);
        window.location.href="/home";
    }

    useEffect(() => {
        const getData = async () => {
            let { data } = await (status === "student" ?  getPostDetail({ id }):getPostDetail2({id}));
            let listRes = await getPostDetailList({ stationVersionId: id });
            if (data.code === 200) {
                setPostObj(data.data);
            } else {
                message.error(data.msg);
            }

            if (listRes.data.code === 200) {
                setNavList(listRes.data.data);
                listRes.data.data[0] && setNavId(listRes.data.data[0].id);
            } else {
                message.error(listRes.data.msg);
            }
        }
        id && getData();
    }, []);

    useEffect(() => {
        const getData = async () => {
            let { data } = await searchNav({ searchTitle, stationVersionId: navItemObj.stationVersionId });
            
            if(data.code === 200){
                setNavList(data.data);
            }
        }
        getData();
    }, [searchTitle])

    useEffect(() => {
        const getNavDeta = async () => {
            let { data } = await getNavDetail({ id: navId });
            if (data.code === 200) {
                setNavItemObj(data.data);
            } else {
                message.error(data.msg);
            }
        }
        navId && getNavDeta();
    }, [navId]);

    return (
        <div id="postDetails">
            <TablePostDetais postObj={postObj} statuss={props.location.state.status?props.location.state.status:""} getDataedList={getDataedList} />
            <CardPost
                setSearch={setSearch}
                navItemObj={navItemObj}
                setNavItemObj={setNavItemObj}
                navId={navId}
                setNavId={setNavId}
                navList={navList} />
        </div>
    );
};

export default PostDetails;